<template>
  <div class="detail_page">
    <div class="content">
      <div class="head_box">
        售后详情
        <div v-if="detailRow.type != 2" class="btn_list">
          <el-button @click="refuse">拒绝售后</el-button>
          <el-button type="primary" @click="handle">同意售后 </el-button>
        </div>
        <div v-else class="btn_list">
          <el-button @click="back">返回</el-button>
        </div>
      </div>
      <div class="detail">
        <div class="order_info">
          <p class="detail_title">订单信息</p>
          <ul class="order_list">
            <li v-for="(item, index) in orderInfo" :key="index">
              <p>{{ item.name }}:</p>
              <p
                :class="[
                  {
                    active: item.type === 1 || item.type === 2 || item.type === 4
                  }
                ]"
              >
                <span @click="getInfo(item)">{{ item.value }}</span>
                <span v-if="item.type === 3 && item.value" class="active" @click="getInfo(item)"
                  >查看物流</span
                >
                <span v-if="item.type === 3 && !item.value">暂无物流信息</span>
              </p>
            </li>
          </ul>
        </div>

        <div class="after_sale_shop">
          <p class="detail_title">售后商品</p>
          <div v-for="(item, index) in shopList" :key="index" class="goods_list">
            <div class="good_details">
              <ul>
                <li>
                  <img :src="item.image" />
                </li>
                <li>
                  <p>{{ item.productName }}</p>
                  <p>{{ item.skuValue }}</p>
                  <p>SKU: {{ item.skuId }}</p>
                </li>
                <li>
                  <p>¥{{ item.productPrice * item.number }}</p>
                  <p>¥{{ `${item.productPrice}*${item.number}` }}</p>
                </li>
                <li>¥{{ item.total }}</li>
              </ul>
            </div>
          </div>
          <div class="total">
            <ul>
              <li></li>
              <li></li>
              <li>退款总金额</li>
              <li>¥{{ total }}</li>
            </ul>
          </div>
        </div>
      </div>

      <div class="after_sales_record">
        <p class="detail_title">协商历史</p>
        <div v-for="(item, index) in recordList" :key="index" class="record_list">
          <div class="record_list_title">
            <p>{{ item.title }}</p>
            <p>{{ item.name }}</p>
            <p>{{ item.time }}</p>
          </div>
          <div class="record_list_content">
            <p>
              <!-- <span>{{ item.type }}:</span> -->
              <span> 留言：{{ item.reason }}</span>
            </p>
            <p v-if="item.images && item.images.length != 0">
              <span>举证图片:</span>
              <el-image
                v-for="(imgItem, imgIndex) in item.images"
                :key="imgIndex"
                style="width: 100px; height: 100px"
                :src="imgItem"
                :preview-src-list="item.images"
              />
            </p>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :fullscreen="!true"
      :before-close="close"
      width="55%"
    >
      <OrderInfo v-if="dialog.type === 1" :order-info-data="orderInfo" :shop-list-data="shopList" />
      <StoreInfo v-if="dialog.type === 2" :dialog="dialog.arr" />
      <Logistics v-if="dialog.type === 3" :logistics-list="dialog" />
      <Buyer v-if="dialog.type === 4" :dialog="dialog.arr" />
      <AfterSales
        v-if="dialog.type === 5"
        :dialog="dialog as any"
        @close="close"
        @dialogs="dialogs"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import OrderInfo from './component/order-info.vue'
  import StoreInfo from './component/store-info.vue'
  import Logistics from './component/logistics.vue'
  import Buyer from './component/buyer.vue'
  import AfterSales from './component/after-sales.vue'
  import { handleAfterOrder } from '@/api/orderApi'
  import { onMounted, ref, toRefs, watch } from 'vue'
  import { ElMessage } from 'element-plus'

  const props = defineProps({
    detailRow: {
      type: Object,
      default: () => ({})
    }
  })

  const emits = defineEmits(['cancel'])

  const { detailRow } = toRefs(props)

  const orderInfo = ref<
    Array<{ name: string; value: string; type: number | string; field: string }>
  >([
    { name: '订单ID', value: '', type: 1, field: 'orderFormid' },
    { name: '售后订单ID', value: '', type: '', field: 'afterFormid' },
    { name: '支付时间', value: '', type: '', field: 'paymentTime' },
    { name: '支付方式', value: '', type: '', field: 'paymentMode' },
    { name: '订单总金额', value: '', type: '', field: 'orderPrice' },
    { name: '店铺名称', value: '', type: 2, field: 'shopName' },
    { name: '物流单号', value: '', type: 3, field: 'deliverFormid' },
    { name: '售后类型', value: '', type: '', field: 'afterType' },
    { name: '买家账户', value: '', type: 4, field: 'customerName' }
  ])

  const shopList = ref<any[]>([])
  const recordList = ref<any[]>([])
  const total = ref(0)
  const dialog = ref<{
    [key: string]: any
    visible?: boolean
    btnName?: string
    afterId?: string
    remark?: string
    arr?:
      | {
          time: string
          context: string
        }[]
      | {
          [key: string]: string
        }
    title?: string
    type?: number
    allow?: boolean
    orderId?: string
    detail?: any
    shopName?: string
    shopCode?: string
    contact?: string
    phone?: string
    customerName?: string
    email?: string
  }>({})
  const afterDetails = ref<{
    orderFormid?: string
    afterFormid?: string
    paymentTime?: string
    paymentMode?: string
    orderPrice?: string
    shopName?: string
    deliverFormid?: string
    afterType?: string
    customerName?: string
    goodsList?: any[]
    refundMoney?: string
    products?: any[]
    refundPrice?: string
    afterHistory?: any[]
  }>({
    orderFormid: '',
    afterFormid: '',
    paymentTime: '',
    paymentMode: '',
    orderPrice: '',
    shopName: '',
    deliverFormid: '',
    afterType: '',
    customerName: '',
    goodsList: [],
    refundMoney: '',
    products: [],
    refundPrice: '',
    afterHistory: []
  })
  const shopId = ref(0)

  watch(
    detailRow,
    (nVal, oVal) => {
      if (nVal) {
        getDetails()
      }
    },
    {
      deep: true
    }
  )

  onMounted(() => {
    getDetails()
  })

  function getDetails() {
    // 模拟数据获取
    const data = {
      orderFormid: detailRow.value.orderFormid || '123456789',
      afterFormid: detailRow.value.afterFormid || '987654321',
      paymentTime: detailRow.value.paymentTime || '2023-05-15 14:30:25',
      paymentMode: detailRow.value.paymentMode || '微信支付',
      orderPrice: detailRow.value.orderPrice || '299.00',
      shopName: detailRow.value.shopName || '官方旗舰店',
      deliverFormid: detailRow.value.deliverFormid || 'SF123456789CN',
      afterType: detailRow.value.afterType || '退货退款',
      customerName: detailRow.value.customerName || '张三',
      products: detailRow.value.goodsList || [
        {
          image: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
          productName: '商品名称示例',
          skuValue: '红色, XL',
          skuId: 'SKU001',
          productPrice: '99.00',
          number: 2,
          total: '198.00'
        }
      ],
      refundPrice: detailRow.value.refundMoney || '198.00',
      afterHistory: [
        {
          title: '发起售后申请',
          name: '张三',
          time: '2023-05-20 10:30:25',
          reason: '商品质量问题',
          images: [
            'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
            'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d85f275jpeg.jpeg'
          ]
        }
      ]
    }

    afterDetails.value = data
    shopId.value = 1001
    const o = data
    getOrderInfo(o)
    shopList.value = o.products
    total.value = o.refundPrice
    recordList.value = o.afterHistory
  }

  function getOrderInfo(o: any) {
    const payChannel: { [key: string]: string } = {
      '1': '微信支付',
      '2': '支付宝支付',
      '3': '余额支付'
    }
    const returnType: { [key: string]: string } = {
      '1': '无售后',
      '2': '退款',
      '3': '退货'
    }
    orderInfo.value.map((item) => {
      item.value = o[item.field] || ''
      if (item.field === 'paymentMode' && payChannel[item.value]) {
        item.value = payChannel[item.value]
      }
      if (item.field === 'afterType' && returnType[item.value]) {
        item.value = returnType[item.value]
      }
    })
  }

  function handle() {
    dialog.value = {
      title: '同意售后',
      visible: true,
      type: 5,
      btnName: '同意售后',
      allow: true,
      orderId: afterDetails.value.orderFormid,
      afterId: afterDetails.value.afterFormid
    }
  }

  function refuse() {
    dialog.value = {
      title: '拒绝售后',
      visible: true,
      type: 5,
      btnName: '拒绝售后',
      orderId: afterDetails.value.orderFormid,
      afterId: afterDetails.value.afterFormid
    }
  }

  function getInfo(item: { type: number | string }) {
    switch (item.type) {
      case 1:
        dialog.value = {
          title: '订单信息',
          visible: true,
          type: item.type
        }
        break

      case 2:
        dialog.value = {
          title: '店铺信息',
          visible: true,
          type: item.type,
          arr: {
            shopName: '官方旗舰店',
            shopCode: 'SF001',
            contact: '李四',
            phone: '13800138000'
          }
        }
        break
      case 3:
        dialog.value = {
          title: '物流信息',
          visible: true,
          type: item.type,
          arr: [
            {
              time: '2023-05-16 15:30:25',
              context: '已发货，快递公司：顺丰速运，运单号：SF123456789CN'
            },
            {
              time: '2023-05-15 10:20:15',
              context: '订单已支付，等待发货'
            }
          ],
          detail: afterDetails
        }
        break

      case 4:
        dialog.value = {
          title: '买家信息',
          visible: true,
          type: item.type,
          arr: {
            customerName: '张三',
            phone: '13900139000',
            email: 'zhangsan@example.com'
          }
        }
        break

      default:
        return
    }
  }

  async function dialogs(arr: { btnName?: string; afterId?: string; remark?: string }) {
    // 检查必要参数是否存在
    if (!arr.afterId) {
      ElMessage.error('缺少订单ID')
      return
    }

    if (arr.btnName === '拒绝售后') {
      try {
        // 调用处理售后订单API
        await handleAfterOrder({
          id: arr.afterId
        })
        ElMessage.success('成功拒绝售后')
        dialog.value.visible = false
        back()
      } catch (error) {
        console.error('拒绝售后失败:', error)
        ElMessage.error('拒绝售后失败')
      }
    } else if (arr.btnName === '同意售后') {
      try {
        // 调用处理售后订单API
        await handleAfterOrder({
          id: arr.afterId
        })
        ElMessage.success('成功同意售后')
        dialog.value.visible = false
        back()
      } catch (error) {
        console.error('同意售后失败:', error)
        ElMessage.error('同意售后失败')
      }
    }
  }

  // 返回
  function back() {
    emits('cancel')
  }

  function close() {
    dialog.value = {}
  }
</script>

<style lang="scss" scoped>
  .detail_page {
    background-color: #fff;
    height: calc(100% - 10px);

    .content {
      .head_box {
        overflow: hidden;
        height: 80px;
        line-height: 80px;
        font-size: 24px;
        border-bottom: 1px solid #e0e5eb;

        .btn_list {
          display: inline-block;
          float: right;
        }
      }

      .detail,
      .after_sales_record {
        min-height: 500px;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0px 0px 10px 0px rgba(51, 51, 51, 0.15);
        border-radius: 4px;
        padding: 1px 30px;
        margin-top: 15px;

        .detail_title {
          font-size: 24px;
          color: #333333;
          position: relative;
          margin: 50px 20px 20px;

          &:before {
            content: '';
            display: block;
            position: absolute;
            top: 5px;
            left: -20px;
            width: 4px;
            height: 24px;
            background-color: #3a68f2;
          }
        }
      }

      .order_info {
        .order_list {
          padding-left: 20px;
          overflow: hidden;
          list-style: none;

          li {
            float: left;
            width: calc(100% / 3);
            margin-bottom: 30px;

            p {
              margin: 0;
              padding: 0;
              display: inline-block;
              font-size: 16px;
              color: #333333;

              &:nth-child(1) {
                margin-right: 20px;
              }

              &:nth-child(2) {
                color: #666666;
              }
            }
          }

          .active {
            color: #3a68f2 !important;

            &:hover {
              cursor: pointer;
            }
          }
        }
      }

      .after_sale_shop {
        .goods_list {
          padding-left: 20px;

          .good_details {
            border-bottom: 1px #e0e5eb solid;

            ul {
              overflow: hidden;
              display: flex;
              margin: 0;
              padding: 30px 0;
              font-size: 16px;

              li {
                flex: 3;
                display: flex;
                text-align: left;

                img {
                  width: 90px;
                  height: 90px;
                  border-radius: 4px;
                  font-size: 16px;
                  color: #333333;
                }

                &:nth-child(2),
                &:nth-child(3) {
                  display: block;
                }

                p {
                  margin: 0;
                  padding: 0;
                  height: 30px;
                  line-height: 30px;
                }
              }
            }
          }
        }

        .total {
          padding-left: 20px;

          ul {
            margin: 0;
            padding: 30px 0;
            display: flex;
            justify-content: flex-end;

            li {
              font-size: 16px;
              color: #333333;
              display: flex;
              width: 90px;

              &:nth-child(4) {
                margin-right: 140px;
              }
            }
          }
        }
      }

      .after_sales_record {
        p {
          margin: 0;
          padding: 0;
          font-size: 16px;
        }

        .record_list {
          padding-left: 20px;

          .record_list_title {
            background: #f7f7f7;
            overflow: hidden;
            margin-bottom: 30px;

            p {
              float: left;
              text-indent: 10px;
              width: calc(100% / 3);
              height: 36px;
              line-height: 36px;
            }
          }

          .record_list_content {
            p {
              overflow: hidden;
              margin-bottom: 30px;

              span {
                display: block;
                float: left;

                &:nth-of-type(2) {
                  text-indent: 10px;
                }

                &:nth-of-type(2) {
                  color: #666666;
                  width: calc(100% - 100px);
                }
              }

              img {
                width: 90px;
                height: 90px;
                border-radius: 4px;
              }
            }
          }
        }
      }
    }
  }

  :deep(.el-dialog__wrapper) {
    .el-dialog__header {
      height: 70px;
      background-color: #3a68f2;

      .el-dialog__title {
        font-size: 24px;
        color: #fff;
      }
    }
  }
</style>
